<?php

class Exts_Security_Certificate extends Exts_Security_SecureData {
	protected $_userAdapter = "Exts_Security_ExtUserAdapter";
	protected $_userAdapterInstance = NULL;
	
	public static function Load ($data){
		$sd = new Exts_Security_Certificate("Loaded");
		$sd->loadSecureData($data);
		return $sd;
	}
	
	/**
	 * @param: $user: UserRow.
	 **/
	
	public function __construct ($user) {
			if ($user == "Loaded") return;
			$hash = $this->_makeHash($user->username, $user->user_id);
			Exts_Security_SecureData::__construct(
													array(	"username" => $user->username, 
															"userId" => $user->user_id, 
															"hash" => $hash	)
													);
		

	}

	
	protected function _getUserAdapterInstance() {
		if (!$this->_userAdapterInstance) {
			$class = $this->_userAdapter;
			$this->_userAdapterInstance = new $class();
			$this->_userAdapterInstance->init();
		}
		return $this->_userAdapterInstance; 
	}
	
	protected function _makeHash($username, $userId) {
		$encrypt = new Zend_Filter_Encrypt(
			array( 'adapter' => 'mcrypt', 'vector' => $this->_vector)
		);
		return  md5($encrypt->filter(md5(strrev($username) . sha1 ($userId))));
	}

	public function validateCertificate() {
			$trueUser = $this->_getUserAdapterInstance()->getUser($this);
			return $this->hash == $this->_makeHash($trueUser->username, $trueUser->user_id);
	}
	
	public function getUser () {
		return $this->_getUserAdapterInstance()->getUser($this);
	}

	
}